package com.lanou.bookstore.category.dao;

import com.lanou.bookstore.category.domain.Category;
import com.lanou.bookstore.utils.C3p0_utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CategoryDao {
    public List<Category> findAll() throws SQLException {
        Connection connection = C3p0_utils.getConnection();
        String sql = "select * from category";
        PreparedStatement ps = connection.prepareStatement(sql);
        ResultSet resultSet = ps.executeQuery();
        List<Category> categoryList = new ArrayList<>();
        while (resultSet.next()) {
            Category category = new Category();
            category.setCid(resultSet.getInt("cid"));
            category.setCname(resultSet.getString("cname"));
            categoryList.add(category);
        }
        return categoryList;
    }

    public void add(String cname) throws SQLException {
        Connection connection = C3p0_utils.getConnection();
        String sql = "insert into category values(null,?)";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1, cname);
        ps.executeUpdate();
    }

    public void deleteByCid(String cid) throws SQLException {
        Connection connection = C3p0_utils.getConnection();
        String sql = "delete from category where cid = ?";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setInt(1, Integer.parseInt(cid));
        ps.executeUpdate();
    }

    public void modifyByCid(String cid, String modCname) throws SQLException {
        Connection connection = C3p0_utils.getConnection();
        String sql = "update category set cname = ? where cid = ?";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1, modCname);
        ps.setInt(2, Integer.parseInt(cid));
        ps.executeUpdate();
    }
}
